<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Website;

/**
 * WebsiteSearch represents the model behind the search form about `backend\models\Website`.
 */
class WebsiteSearch extends Website
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'page_view', 'category_id', 'update_at', 'create_at'], 'integer'],
            [['url', 'title', 'desc'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Website::find();
        $query = $query->orderby(['page_view' => SORT_DESC]);
        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pagesize' => '10',
            ]
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        if (isset($this->category_id) && $this->category_id != '') {

            // 查询子类下面的所有数据
            $category_ids = Yii::$app->db->createCommand('call sp_showChildLst("' . $this->category_id . '")')->queryAll();

            $ids = array();
            foreach ($category_ids as $cate) {

                array_push($ids, $cate['id']);
            }

            $query->andWhere(['in', 'category_id', $ids]);
        }

        if (isset($this->title) && $this->title != '') {
           $query->andWhere(['and', ['or', ['like', 'url', $this->title], ['like', 'title', $this->title]]]);
        }
        $query->andFilterWhere(['like', 'desc', $this->desc]);

        Yii::$app->db->cache(function($db) use($dataProvider){
            $dataProvider->prepare();
        }, 60);
        return $dataProvider;
    }
}
